package com.itheima.health.File;

import com.alibaba.fastjson.JSON;
import com.itheima.health.common.MessageConst;
import com.itheima.health.common.UrlMap;
import com.itheima.health.entity.Result;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 登录过滤器
 *
 * @author mhw
 * @since 2022/11/22 12:34
 */
@WebFilter(filterName = "LoginFile",urlPatterns = "/")//过滤器配置
@Slf4j //输出
@Component //放入spring容器中
public class LoginFile implements Filter {

    @Autowired
    private UserService userService;

    //符合不需要拦截判断的路径
    private static final String[] URLS = new String[]{
            "/user/login",
            "/mobile/validateCode/send",
            "/mobile/login/smsLogin",
            "/user/login","/mobile/validateCode/send","/mobile/login/smsLogin",
            "/mobile/**" //放行所有移动端请求
    };
    //路径匹配器
    private static final AntPathMatcher MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求路径
        String requestURI = request.getRequestURI();
        log.info("requestURI=====>{}",requestURI);
        //使用增强for回去放行路径
        for (String url : URLS) {
            //路径匹配
            boolean match = MATCHER.match(url, requestURI);
            if (match){
                log.info("放行指定请求");
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        }
        //判断是否已经登录，如果登录就放行
        Integer id = (Integer) request.getSession().getAttribute(MessageConst.USER_ID);
        if (id !=null){
            //查询role表的id
            Integer byRoleId = userService.findByRoleId(id);
            //通过roleid获取permission表的id
            Integer[] permissionId = userService.findPermissionId(byRoleId);
            //获取对应的权限
            List<String> keywords = userService.findkeyword(permissionId);
            Map map = UrlMap.Map();
            String requestURIkeyWord = (String) map.get(requestURI);
            for (String keyword : keywords) {
                if (requestURIkeyWord.equals(keyword)){
                    filterChain.doFilter(servletRequest,servletResponse);
                    return;
                }
            }
            log.info("放行后端登录");
            //response.setContentType("application/json; charset=UTF-8");
            response.sendRedirect("http://localhost:18080/pages/login.html");
            //response.getWriter().write(JSON.toJSONString(new Result(false, MessageConst.PERMISSION)));
            return;
        }
        //判断是否为手机端登录
        String employee_id = (String) request.getSession().getAttribute(MessageConst.EMPLOYEE_ID);
        if (employee_id != null){
            log.info("放行前端登录");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        // 5.如果未登录，返回未登录的错误信息，前端处理错误信息显示
        response.setContentType("application/json; charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(new Result(false, MessageConst.LOGIN_FAIL)));
    }
}
